<?php namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Orders;
use App\ShopInfo;
use App\SynchRecord;
use App\User;
use App\UserInfo;
use App\Vip;
use App\VipInfo;
use TopClient;
use Illuminate\Http\Request;
use TopAuthTokenCreateRequest;
use Log;

class AlidataController extends Controller
{
    public function toAuth(Request $request){
        $url = "https://oauth.taobao.com/authorize?response_type=code&client_id=28127552&redirect_uri=http://admin.xinyidemy.com/api/ali/getAccessToken&state=1212&view=web";
        return redirect()->to($url);
    }

    public function getOrderData(Request $q){
        $shopInfoId = $q->get('shop_info_id');
        $thatShopInfo = ShopInfo::whereId($shopInfoId)->first();

        if(!$thatShopInfo)
            return response()->json(['level'=>'error','message'=>"商家信息不存在","data"=>"to_auth"]);

        $s = self::getMillisecond();
        if((int)$thatShopInfo->expire_time < $s){
            return response()->json(['level'=>'error','message'=>"授权已过期，请重新授权","data"=>"to_auth"]);
        }

        $accessToken = $thatShopInfo->access_token;

        $page     = !is_null($q->get('page')) ? $q->get('page') : 1;
        $day      = !is_null($q->get('day')) ? $q->get('day') : 1;
        $startTime= $q->get('start_time');
        $endTime  = $q->get('end_time');
        $pageSize = !is_null($q->get('page_size')) ? $q->get('page_size') : 20;

//        $start_time = "";
//        $end_time = "";
//        if(!is_null($start_time) && trim($startTime) != ""){
//            $start_time = $startTime;
//
//            if(!is_null($end_time) && trim($end_time) != ""){
//                $end_time = $endTime;
//            }else{
//                $end_time = date('Y-m-d H:i:s',time());
//            }
//        }else{
//            $start_time = date('Y-m-d H:i:s', time() - $day * 24 * 60 * 60);
//            $end_time   = date('Y-m-d H:i:s',time());
//        }

        $application = new \ihipop\TaobaoTop\Application([
            'topClient' => [
                'apiKey'          => '28127552',
                'apiSecret'       => 'bb77b9e569cab71b442198cbf3e7ba38',
                'secureRandomNum' => null, // `如果你应用开启了加密 就设置这个 否则请设置为null`
                'autoDecrypt'     => true, // `同上 如果你应用开启了加密 需要自动解密 就打开这个 否则请关闭,设置为false`
            ],
            'providers' => [
                'http' => \ihipop\TaobaoTop\providers\GuzzleHttpClientServiceProvider::class,
            ],
        ]);
        $topClient   = $application->topClient;

        $next = true;

        $newOrderNum = 0;
        $allOrderNum = 0;
        $newVipNum   = 0;

        while ($next){
            $request = new \ihipop\TaobaoTop\requests\taobao\GetTradesSold();
            $request->setFields([
                'seller_nick',
                'buyer_nick',
                'post_fee',
                'receiver_name',
                'receiver_state',
                'receiver_address',
                'receiver_city',
                'receiver_zip',
                'receiver_mobile',
                'receiver_phone',
                'consign_time',
                'received_payment',
                'receiver_country',
                'receiver_town',
                'tid',
                'num',
                'num_iid',
                'status',
                'title',
                'type',
                'price',//其他字段略
                'pic_path',
                'payment',
                'seller_rate',
                'post_fee',
                'total_fee',
                'discount_fee',
                'has_post_fee',
                'created',
                'pay_time',
                'end_time',
                'buyer_memo',
                'receiver_district',
                'delivery_time',
                'collect_time',
                'dispatch_time',
                'sign_time',
            ])->setType([
                'guarantee_trade',
                'auto_delivery',
                'ec',
                'cod',
                'step',
                'tmall_i18n',
                'nopaid',
            ])->setUseHasNext('true')->setPageSize($pageSize)->setPageNo($page);
            $request->setStartCreated(date('Y-m-d H:i:s', time() - $day * 24 * 60 * 60))->setEndCreated(date('Y-m-d H:i:s',time()));

            $response = $topClient->execute($request, $accessToken);
//        $response = $topClient->execute($request, $thatShopInfo->access_token);

            $next = $response['has_next'];
            if($next){
                $page++;
            }

            if(isset($response['trades']) && count($response['trades'])>0){
                $allOrderNum = count($response['trades']);
                foreach ($response['trades'] as $trades){
                    $thatOrder = Orders::whereTid($trades["tid"])->first();
                    if(!$thatOrder){
                        $newOrderNum = $newOrderNum + 1;
                        if(isset($trades["receiver_mobile"])){
                            $thatVip = Vip::wherePhone($trades["receiver_mobile"])->first();
                            if(!$thatVip){
                                $thatVip = new Vip();
                                $thatVip->phone = $trades["receiver_mobile"];
                                $thatVip->reg_time = $trades["created"];
                                $thatVip->from_type = 'tmall';
                                $thatVip->integral= 1;
                                $thatVip->save();

                                $newVipNum++;
                            }

                            $thatVipInfo = VipInfo::whereNickname($trades["buyer_nick"])->first();
                            if(!$thatVipInfo){
                                $thatVipInfo = new VipInfo();
                                $thatVipInfo->vip_id = $thatVip->id;
                                $thatVipInfo->nickname = $trades["buyer_nick"];
                                $thatVipInfo->realname =  $trades["receiver_name"];
                                $thatVipInfo->province = $trades["receiver_state"];
                                $thatVipInfo->city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                                $thatVipInfo->area = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                                $thatVipInfo->detail = $trades["receiver_address"];
                                $thatVipInfo->save();
                            }

                            $newOrder = new Orders();
                            $newOrder->vip_id = $thatVip->id;
                            $newOrder->seller_nick = $trades["seller_nick"];
                            $newOrder->pic_path = isset($trades["pic_path"]) ? $trades["pic_path"] :null;
                            $newOrder->payment = $trades["payment"];
                            $newOrder->seller_rate = $trades["seller_rate"];
                            $newOrder->post_fee = $trades["post_fee"];
                            $newOrder->receiver_name = $trades["receiver_name"];
                            $newOrder->receiver_state = $trades["receiver_state"];
                            $newOrder->receiver_town = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                            $newOrder->receiver_address = $trades["receiver_address"];
                            $newOrder->receiver_zip = $trades["receiver_zip"];
                            $newOrder->receiver_mobile = $trades["receiver_mobile"];
                            $newOrder->receiver_phone = isset($trades["receiver_phone"]) ? $trades["receiver_phone"]:null;
                            $newOrder->consign_time = isset($trades["consign_time"]) ? $trades["consign_time"]:null;
                            $newOrder->received_payment = isset($trades["received_payment"]) ? $trades["received_payment"]:null;
                            $newOrder->tid = $trades["tid"];
                            $newOrder->num = isset($trades["num"]) ? $trades["num"] : 0;
                            $newOrder->num_iid = isset($trades["num_iid"])?$trades["num_iid"]:0;
                            $newOrder->status = $trades["status"];
                            $newOrder->title = $trades["title"];
                            $newOrder->type = $trades["type"];
                            $newOrder->price = isset($trades["price"])?$trades["price"]:0;
                            $newOrder->total_fee = $trades["total_fee"];
                            $newOrder->discount_fee = $trades["discount_fee"];
                            $newOrder->has_post_fee = isset($trades["has_post_fee"]) ? $trades["has_post_fee"] : 0;
                            $newOrder->created = $trades["created"];
                            $newOrder->pay_time = isset($trades["pay_time"]) ? $trades["pay_time"] : null;
                            $newOrder->end_time = isset($trades["end_time"]) ? $trades["end_time"] : null;
                            $newOrder->buyer_memo = isset($trades["buyer_memo"]) ? $trades["buyer_memo"] : null;
                            $newOrder->buyer_nick = $trades["buyer_nick"];
                            $newOrder->receiver_city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                            $newOrder->receiver_district = isset($trades["receiver_district"]) ? $trades["receiver_district"] : null;
                            $newOrder->delivery_time = isset($trades["delivery_time"])?$trades["delivery_time"]:null;
                            $newOrder->collect_time = isset($trades["collect_time"])?$trades["collect_time"]:null;
                            $newOrder->dispatch_time = isset($trades["dispatch_time"]) ? $trades["dispatch_time"] :null;
                            $newOrder->sign_time = isset($trades["sign_time"]) ? $trades["sign_time"] : null;
                            $newOrder->from_type = 'tmall';
                            $newOrder->save();
                        }
                    }else{
                        $thatOrder->payment = $trades["payment"];
                        $thatOrder->seller_rate = $trades["seller_rate"];
                        $thatOrder->post_fee = $trades["post_fee"];
                        $thatOrder->receiver_name = $trades["receiver_name"];
                        $thatOrder->receiver_state = $trades["receiver_state"];
                        $thatOrder->receiver_town = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                        $thatOrder->receiver_address = $trades["receiver_address"];
                        $thatOrder->receiver_zip = $trades["receiver_zip"];
                        $thatOrder->receiver_mobile = $trades["receiver_mobile"];
                        $thatOrder->receiver_phone = isset($trades["receiver_phone"]) ? $trades["receiver_phone"]:null;
                        $thatOrder->consign_time = isset($trades["consign_time"]) ? $trades["consign_time"]:null;
                        $thatOrder->received_payment = isset($trades["received_payment"]) ? $trades["received_payment"]:null;
                        $thatOrder->tid = $trades["tid"];
                        $thatOrder->num = isset($trades["num"]) ? $trades["num"] : 0;
                        $thatOrder->num_iid = isset($trades["num_iid"])?$trades["num_iid"]:0;
                        $thatOrder->status = $trades["status"];
                        $thatOrder->title = $trades["title"];
                        $thatOrder->type = $trades["type"];
                        $thatOrder->price = isset($trades["price"])?$trades["price"]:0;
                        $thatOrder->total_fee = $trades["total_fee"];
                        $thatOrder->discount_fee = $trades["discount_fee"];
                        $thatOrder->has_post_fee = isset($trades["has_post_fee"]) ? $trades["has_post_fee"] : 0;
                        $thatOrder->created = $trades["created"];
                        $thatOrder->pay_time = isset($trades["pay_time"]) ? $trades["pay_time"] : null;
                        $thatOrder->end_time = isset($trades["end_time"]) ? $trades["end_time"] : null;
                        $thatOrder->buyer_memo = isset($trades["buyer_memo"]) ? $trades["buyer_memo"] : null;
                        $thatOrder->buyer_nick = $trades["buyer_nick"];
                        $thatOrder->receiver_city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                        $thatOrder->receiver_district = isset($trades["receiver_district"]) ? $trades["receiver_district"] : null;
                        $thatOrder->delivery_time = isset($trades["delivery_time"])?$trades["delivery_time"]:null;
                        $thatOrder->collect_time = isset($trades["collect_time"])?$trades["collect_time"]:null;
                        $thatOrder->dispatch_time = isset($trades["dispatch_time"]) ? $trades["dispatch_time"] :null;
                        $thatOrder->sign_time = isset($trades["sign_time"]) ? $trades["sign_time"] : null;
                        $thatOrder->from_type = 'tmall';
                        $thatOrder->save();
                    }
                }
            }
        }

        self::setSynchRecord($allOrderNum,$newOrderNum,$newVipNum,"手动更新订单完成",1);

        return response()->json(['level'=>'success','message'=>"同步完成","data"=>$newOrderNum]);
    }

    public function autoSynchOrder(Request $request){
        $thatShopInfo = ShopInfo::first();

        if(!$thatShopInfo){
            self::setSynchRecord(0,0,0,"手动更新数据失败，原因：商家信息不存在",0);
        }

        $s = self::getMillisecond();
        if((int)$thatShopInfo->expire_time < $s){
            self::setSynchRecord(0,0,0,"手动更新数据失败，原因：授权已过期",0);
        }

        $accessToken = $thatShopInfo->access_token;

        $application = new \ihipop\TaobaoTop\Application([
            'topClient' => [
                'apiKey'          => '28127552',
                'apiSecret'       => 'bb77b9e569cab71b442198cbf3e7ba38',
                'secureRandomNum' => null, // `如果你应用开启了加密 就设置这个 否则请设置为null`
                'autoDecrypt'     => true, // `同上 如果你应用开启了加密 需要自动解密 就打开这个 否则请关闭,设置为false`
            ],
            'providers' => [
                'http' => \ihipop\TaobaoTop\providers\GuzzleHttpClientServiceProvider::class,
            ],
        ]);
        $topClient   = $application->topClient;

        $next = true;

        $newOrderNum = 0;
        $allOrderNum = 0;
        $newVipNum   = 0;
        $pageSize    = 20;
        $page        = 1;

        while ($next){
            $request = new \ihipop\TaobaoTop\requests\taobao\GetTradesSoldIncrement();
            $request->setFields([
                'seller_nick',
                'buyer_nick',
                'post_fee',
                'receiver_name',
                'receiver_state',
                'receiver_address',
                'receiver_city',
                'receiver_zip',
                'receiver_mobile',
                'receiver_phone',
                'consign_time',
                'received_payment',
                'receiver_country',
                'receiver_town',
                'tid',
                'num',
                'num_iid',
                'status',
                'title',
                'type',
                'price',//其他字段略
                'pic_path',
                'payment',
                'seller_rate',
                'post_fee',
                'total_fee',
                'discount_fee',
                'has_post_fee',
                'created',
                'modified',
                'pay_time',
                'end_time',
                'buyer_memo',
                'receiver_district',
                'delivery_time',
                'collect_time',
                'dispatch_time',
                'sign_time',
            ])->setType([
                'guarantee_trade',
                'auto_delivery',
                'ec',
                'cod',
                'step',
                'tmall_i18n',
                'nopaid',
            ])->setUseHasNext('true')->setPageSize($pageSize)->setPageNo($page);
            $request->setStartModified(date('Y-m-d 00:00:00', time()))->setEndModified(date('Y-m-d H:i:s',time()));

            $response = $topClient->execute($request, $accessToken);
//        $response = $topClient->execute($request, $thatShopInfo->access_token);

            $next = $response['has_next'];
            if($next){
                $page++;
            }

            if(isset($response['trades']) && count($response['trades'])>0){
                $allOrderNum = count($response['trades']);
                foreach ($response['trades'] as $trades){
                    $thatOrder = Orders::whereTid($trades["tid"])->first();
                    if(!$thatOrder){
                        $newOrderNum = $newOrderNum + 1;
                        if(isset($trades["receiver_mobile"])){
                            $thatVip = Vip::wherePhone($trades["receiver_mobile"])->first();
                            if(!$thatVip){
                                $thatVip = new Vip();
                                $thatVip->phone = $trades["receiver_mobile"];
                                $thatVip->reg_time = $trades["created"];
                                $thatVip->from_type = 'tmall';
                                $thatVip->integral= 1;
                                $thatVip->save();

                                $newVipNum++;
                            }

                            $thatVipInfo = VipInfo::whereNickname($trades["buyer_nick"])->first();
                            if(!$thatVipInfo){
                                $thatVipInfo = new VipInfo();
                                $thatVipInfo->vip_id = $thatVip->id;
                                $thatVipInfo->nickname = $trades["buyer_nick"];
                                $thatVipInfo->realname =  $trades["receiver_name"];
                                $thatVipInfo->province = $trades["receiver_state"];
                                $thatVipInfo->city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                                $thatVipInfo->area = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                                $thatVipInfo->detail = $trades["receiver_address"];
                                $thatVipInfo->save();
                            }

                            $newOrder = new Orders();
                            $newOrder->vip_id = $thatVip->id;
                            $newOrder->seller_nick = $trades["seller_nick"];
                            $newOrder->pic_path = isset($trades["pic_path"]) ? $trades["pic_path"] :null;
                            $newOrder->payment = $trades["payment"];
                            $newOrder->seller_rate = $trades["seller_rate"];
                            $newOrder->post_fee = $trades["post_fee"];
                            $newOrder->receiver_name = $trades["receiver_name"];
                            $newOrder->receiver_state = $trades["receiver_state"];
                            $newOrder->receiver_town = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                            $newOrder->receiver_address = $trades["receiver_address"];
                            $newOrder->receiver_zip = $trades["receiver_zip"];
                            $newOrder->receiver_mobile = $trades["receiver_mobile"];
                            $newOrder->receiver_phone = isset($trades["receiver_phone"]) ? $trades["receiver_phone"]:null;
                            $newOrder->consign_time = isset($trades["consign_time"]) ? $trades["consign_time"]:null;
                            $newOrder->received_payment = isset($trades["received_payment"]) ? $trades["received_payment"]:null;
                            $newOrder->tid = $trades["tid"];
                            $newOrder->num = isset($trades["num"]) ? $trades["num"] : 0;
                            $newOrder->num_iid = isset($trades["num_iid"])?$trades["num_iid"]:0;
                            $newOrder->status = $trades["status"];
                            $newOrder->title = $trades["title"];
                            $newOrder->type = $trades["type"];
                            $newOrder->price = isset($trades["price"])?$trades["price"]:0;
                            $newOrder->total_fee = $trades["total_fee"];
                            $newOrder->discount_fee = $trades["discount_fee"];
                            $newOrder->has_post_fee = isset($trades["has_post_fee"]) ? $trades["has_post_fee"] : 0;
                            $newOrder->created = $trades["created"];
                            $newOrder->pay_time = isset($trades["pay_time"]) ? $trades["pay_time"] : null;
                            $newOrder->end_time = isset($trades["end_time"]) ? $trades["end_time"] : null;
                            $newOrder->buyer_memo = isset($trades["buyer_memo"]) ? $trades["buyer_memo"] : null;
                            $newOrder->buyer_nick = $trades["buyer_nick"];
                            $newOrder->receiver_city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                            $newOrder->receiver_district = isset($trades["receiver_district"]) ? $trades["receiver_district"] : null;
                            $newOrder->delivery_time = isset($trades["delivery_time"])?$trades["delivery_time"]:null;
                            $newOrder->collect_time = isset($trades["collect_time"])?$trades["collect_time"]:null;
                            $newOrder->dispatch_time = isset($trades["dispatch_time"]) ? $trades["dispatch_time"] :null;
                            $newOrder->sign_time = isset($trades["sign_time"]) ? $trades["sign_time"] : null;
                            $newOrder->from_type = 'tmall';
                            $newOrder->save();
                        }
                    }else{
                        $thatOrder->payment = $trades["payment"];
                        $thatOrder->seller_rate = $trades["seller_rate"];
                        $thatOrder->post_fee = $trades["post_fee"];
                        $thatOrder->receiver_name = $trades["receiver_name"];
                        $thatOrder->receiver_state = $trades["receiver_state"];
                        $thatOrder->receiver_town = isset($trades["receiver_town"]) ? $trades["receiver_town"] : null;
                        $thatOrder->receiver_address = $trades["receiver_address"];
                        $thatOrder->receiver_zip = $trades["receiver_zip"];
                        $thatOrder->receiver_mobile = $trades["receiver_mobile"];
                        $thatOrder->receiver_phone = isset($trades["receiver_phone"]) ? $trades["receiver_phone"]:null;
                        $thatOrder->consign_time = isset($trades["consign_time"]) ? $trades["consign_time"]:null;
                        $thatOrder->received_payment = isset($trades["received_payment"]) ? $trades["received_payment"]:null;
                        $thatOrder->tid = $trades["tid"];
                        $thatOrder->num = isset($trades["num"]) ? $trades["num"] : 0;
                        $thatOrder->num_iid = isset($trades["num_iid"])?$trades["num_iid"]:0;
                        $thatOrder->status = $trades["status"];
                        $thatOrder->title = $trades["title"];
                        $thatOrder->type = $trades["type"];
                        $thatOrder->price = isset($trades["price"])?$trades["price"]:0;
                        $thatOrder->total_fee = $trades["total_fee"];
                        $thatOrder->discount_fee = $trades["discount_fee"];
                        $thatOrder->has_post_fee = isset($trades["has_post_fee"]) ? $trades["has_post_fee"] : 0;
                        $thatOrder->created = $trades["created"];
                        $thatOrder->modified = isset($trades["modified"]) ? $trades["modified"] : null;
                        $thatOrder->pay_time = isset($trades["pay_time"]) ? $trades["pay_time"] : null;
                        $thatOrder->end_time = isset($trades["end_time"]) ? $trades["end_time"] : null;
                        $thatOrder->buyer_memo = isset($trades["buyer_memo"]) ? $trades["buyer_memo"] : null;
                        $thatOrder->buyer_nick = $trades["buyer_nick"];
                        $thatOrder->receiver_city = isset($trades["receiver_city"]) ? $trades["receiver_city"] : null;
                        $thatOrder->receiver_district = isset($trades["receiver_district"]) ? $trades["receiver_district"] : null;
                        $thatOrder->delivery_time = isset($trades["delivery_time"])?$trades["delivery_time"]:null;
                        $thatOrder->collect_time = isset($trades["collect_time"])?$trades["collect_time"]:null;
                        $thatOrder->dispatch_time = isset($trades["dispatch_time"]) ? $trades["dispatch_time"] :null;
                        $thatOrder->sign_time = isset($trades["sign_time"]) ? $trades["sign_time"] : null;
                        $thatOrder->from_type = 'tmall';
                        $thatOrder->save();
                    }
                }
            }
        }

        self::setSynchRecord($allOrderNum,$newOrderNum,$newVipNum,"自动更新订单完成",1);

        return response()->json(['level'=>'success','message'=>"同步完成","data"=>$newOrderNum]);
    }

    public function getSychMsg(Request $request){
        $allSynchRecords = SynchRecord::whereIsRead(0)->get();
        $lastSynch = SynchRecord::whereIsRead(1)->orderBy("id","desc")->first();
        $second = 0;
        if($lastSynch){
            $second = 300 - (time() - strtotime($lastSynch->created_at));
        }

        if(count($allSynchRecords) > 0){
            return response()->json(['level'=>'success',"data"=>1,"second"=>$second]);
        }else{
            return response()->json(['level'=>'success',"data"=>0,"second"=>$second]);
        }
    }

    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }

    public function getAccessToken(Request $request){
        $code = $request->get('code');

        $url = 'https://oauth.taobao.com/token';
        $postfields= array('grant_type'=>'authorization_code',
            'client_id'=>'28127552',
            'client_secret'=>'bb77b9e569cab71b442198cbf3e7ba38',
            'code'=>$code,
            'redirect_uri'=>'https://admin.xinyidemy.com');
        $post_data = '';
        foreach($postfields as $key=>$value){
            $post_data .="$key=".urlencode($value)."&";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//指定post数据
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));  //添加变量
        $output = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //正确时返回200
        curl_close($ch);

        if($httpStatusCode == 200){
            $dataJson = json_decode($output);

            $taobaoUserId = $dataJson->taobao_user_id;

            $thatShopInfo = ShopInfo::whereSUserId($taobaoUserId)->first();
            if(!$thatShopInfo){
                $thatShopInfo = new ShopInfo();
                $thatShopInfo->s_user_id = $dataJson->taobao_user_id;
                $thatShopInfo->s_user_nick = urldecode($dataJson->taobao_user_nick);
            }
            $thatShopInfo->open_uid = $dataJson->taobao_open_uid;
            $thatShopInfo->access_token = $dataJson->access_token;
            $thatShopInfo->expire_time = $dataJson->expire_time;
            $thatShopInfo->refresh_token = $dataJson->refresh_token;
            $thatShopInfo->token_type = $dataJson->token_type;
            $thatShopInfo->type = "tmall";
            $thatShopInfo->save();

            $start_time = date('Y-m-d H:i:s', time() - 90 * 24 * 60 * 60);
            $end_time   = date('Y-m-d H:i:s',time());
            return redirect()->to(route('Admin.Home.orderList')."?new_auth=".$thatShopInfo->id."&start_time=".$start_time."&end_time=".$end_time);
        }else{
            echo "授权失败，请联系管理员";
        }
    }

    private function get_microtime_format($time)
    {
        if(strstr($time,'.'))
        {
            sprintf("%01.3f",$time);
            list($usec,$sec) = explode(".", $time);
            $sec = str_pad($sec,3,"0",STR_PAD_RIGHT);
        }else
        {
            $usec = $time;
            $sec = "000";
        }
        $date = date("Y-m-d H:i:s.x", $usec);
        return str_replace("x", $sec, $date);
    }

    public static function setSynchRecord($allOrderNum=0,$newOrderNum=0,$newVipNum=0,$message=null,$status=1){
        $thatSynchRecord = new SynchRecord();
        $thatSynchRecord->all_order_num = $allOrderNum;
        $thatSynchRecord->new_order_num = $newOrderNum;
        $thatSynchRecord->new_vip_num   = $newVipNum;
        $thatSynchRecord->from_type     = "tmall";
        $thatSynchRecord->message       = $message;
        $thatSynchRecord->status        = $status;
        $thatSynchRecord->save();
    }
}